package cn.innosmart.aq.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import cn.innosmart.aq.R;
import cn.innosmart.aq.adapter.WorkLogImageAdapter;
import cn.innosmart.aq.bean.WorkLog;
import cn.innosmart.aq.bean.WorkLogTemp;
import cn.innosmart.aq.customize.NoScrollGridView;
import cn.innosmart.aq.customize.addview.AddProperty.Property;
import cn.innosmart.aq.customize.datetimepicker.CustomPickerDialog;
import cn.innosmart.aq.util.INetworkInteractUtil;
import cn.innosmart.aq.util.LocationUtil;
import cn.innosmart.aq.util.NetworkInteractUtil;
import cn.innosmart.aq.view.activity.base.BaseActivity;

/**
 * Created by David on 2015/12/1.
 */
public class WorkLogAddActivity extends BaseActivity implements INetworkInteractUtil {
    private final int EXIT = 0;
    private NetworkInteractUtil interactUtil;
    private Toolbar toolbar;
    private TextView tvTile;
    private LinearLayout llPropertyContent;
    private Button btCommit;
    private NoScrollGridView gvImage;
    private WorkLogImageAdapter workLogImageAdapter;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case EXIT:
                    exit();
                    break;
            }
        }
    };
    private WorkLogTemp workLogTemp;
    private ArrayList<Property> properties = new ArrayList<>();
    private ArrayList<EditText> inputValues = new ArrayList<>();
    private View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            Property property = (Property) v.getTag();
            if (hasFocus) {
                // 此处为得到焦点时的处理内容
            } else {
                // 此处为失去焦点时的处理内容
                EditText editText = (EditText) v;
                String value = editText.getText().toString().trim();
                property.setValue(value);
            }
        }
    };
    private TextView tvLocation;
    private EditText etPs;
    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (checkProperty()) {
                showToast(getString(R.string.activity_work_log_add_isrequired_need));
                return;
            }
            JSONObject content = new JSONObject();
            JSONArray contentParams = new JSONArray();
            for (Property property : properties) {
                contentParams.put(property.getValue());
            }
            String location = tvLocation.getText().toString().trim();
            if (TextUtils.isEmpty(location)) {
                return;
            }
            if (location.equals(R.string.activity_worklogadd_location_failed)) {
                return;
            }
            loadingDialog();
            String ps = etPs.getText().toString().trim();
            try {
                content.put("property", contentParams);
                content.put("location", location);
                content.put("ps", ps);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            JSONObject jsonParams = new JSONObject();
            try {
                jsonParams.put("template", workLogTemp.getId());
                jsonParams.put("time", System.currentTimeMillis() / 1000);
                jsonParams.put("content", content.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            interactUtil.addWorkLog(jsonParams);
        }
    };
    private String flag = null;
    private WorkLog workLog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_work_log_add);
        initView();
        setBar();
        interactUtil = new NetworkInteractUtil(this);
    }

    private void initView() {
        Intent intent = getIntent();
        String workLogTempStr = intent.getStringExtra("worklogtemp");
        String workLogStr = intent.getStringExtra("worklog");
        flag = intent.getStringExtra("flag");
        tvLocation = (TextView) findViewById(R.id.tv_location);
        etPs = (EditText) findViewById(R.id.et_ps);
        tvTile = (TextView) findViewById(R.id.tv_title);
        btCommit = (Button) findViewById(R.id.bt_commit);
        gvImage = (NoScrollGridView) findViewById(R.id.gv_image);
        llPropertyContent = (LinearLayout) findViewById(R.id.ll_property_content);
//        if (TextUtils.isEmpty(flag)) {
//            return;
//        }
        try {
            workLogTemp = new WorkLogTemp(new JSONObject(workLogTempStr));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String title = getString(R.string.format_work_log_title) + workLogTemp.getTitle();
        tvTile.setText(title);
        if (!flag.equals("check")) {
            btCommit.setOnClickListener(mOnClickListener);
            workLogImageAdapter = new WorkLogImageAdapter(this);
            gvImage.setVisibility(View.GONE);
            gvImage.setAdapter(workLogImageAdapter);
            gvImage.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    //show the select activity
                    String url = null;
                    if (workLogImageAdapter.getItem(position) != null) {
                        url = (String) workLogImageAdapter.getItem(position);
                    }
                    if (url == null) {
                        Intent intent = new Intent(WorkLogAddActivity.this, ImageSelectActivity.class);
                        intent.putExtra("flag", 2);
                        startActivityForResult(intent, 1002);
                        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                    } else {
                        Intent intent = new Intent(WorkLogAddActivity.this, ShowWorkLogImageActivity.class);
                        intent.putExtra("url", url);
                        startActivityForResult(intent, 1003);
                        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                    }
                }
            });
            tvLocation.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startLocation();
                }
            });
            startLocation();
        } else {
            try {
                workLog = new WorkLog(new JSONObject(workLogStr));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            tvLocation.setText(workLog.getLocation());
            etPs.setText(workLog.getPs());
            tvLocation.setEnabled(false);
            etPs.setEnabled(false);
            btCommit.setVisibility(View.GONE);
        }
        ArrayList<JSONObject> jsonColumns = workLogTemp.getColumns();
        properties = new ArrayList<>();
        for (int i = 0; i < jsonColumns.size(); i++) {
            JSONObject jsonObject = jsonColumns.get(i);
            Property property = new Property();
            try {
                property.setType(jsonObject.getString("type"));
                property.setIsRequired(jsonObject.getBoolean("isRequired"));
                property.setTitle(jsonObject.getString("name"));
                if (workLog != null){
                    if(workLog.getProperties().get(i)!=null){
                        property.setValue((String) workLog.getProperties().get(i));
                    }else{
                        property.setValue("");
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            properties.add(property);
        }
        for (Property property : properties) {
            if (property.getType().equals("TEXT")) {
                llPropertyContent.addView(addTextView(property));
            } else if (property.getType().equals("NUM")) {
                llPropertyContent.addView(addNumView(property));
            } else if (property.getType().equals("DATE")) {
                llPropertyContent.addView(addDateView(property));
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1002 && resultCode == 1002) {
            String url = data.getStringExtra("imageurl");
            workLogImageAdapter.addUrl(url);
        } else if (requestCode == 1003 && resultCode == 1003) {
            String url = data.getStringExtra("url");
            workLogImageAdapter.removeUrl(url);
        }
    }

    private void startLocation() {
        tvLocation.setText(R.string.activity_worklogadd_locationing);
        if (LocationUtil.getInstance().mLocationClient.isStarted()) {
            LocationUtil.getInstance().mLocationClient.stop();
        }
        LocationUtil.getInstance().startLocation(new LocationUtil.LocationCallBack() {
            @Override
            public void onSuccessResultCallBack(final String address) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvLocation.setText(address);
                    }
                });
            }

            @Override
            public void onFailedCallBack() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvLocation.setText(R.string.activity_worklogadd_location_failed);
                    }
                });
            }
        });
    }

    public boolean checkProperty() {
        if (properties == null)
            properties = new ArrayList<>();
        for (Property property : properties) {
            if (TextUtils.isEmpty(property.getValue())) {
                Object tag = property.getTag();
                if (tag instanceof EditText) {
                    property.setValue(((EditText) tag).getText().toString().trim());
                }
                if (tag instanceof TextView) {
                    property.setValue(((TextView) tag).getText().toString().trim());
                }
            }
            if (property.isRequired()) {
                if (TextUtils.isEmpty(property.getValue())) {
                    return true;
                }
            }
        }
        return false;
    }

    private View addTextView(Property property) {
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        LayoutInflater inflater3 = LayoutInflater.from(this);
        View view = inflater3.inflate(R.layout.add_text_view, null);
        TextView tvPropertyTitle = (TextView) view.findViewById(R.id.tv_property_title);
        EditText etPropertyValue = (EditText) view.findViewById(R.id.et_property_value);
        tvPropertyTitle.setText(property.getTitle());
        property.setTag(etPropertyValue);
        if (property.isRequired()) {
            etPropertyValue.setHint(R.string.add_work_log_property_text_isrequired_hint);
        } else {
            etPropertyValue.setHint(R.string.add_work_log_property_text_hint);
        }
        if (property.getValue() != null && flag.equals("check")) {
            etPropertyValue.setText(property.getValue());
            etPropertyValue.setEnabled(false);
        }
        etPropertyValue.setTag(property);
        inputValues.add(etPropertyValue);
        etPropertyValue.setOnFocusChangeListener(onFocusChangeListener);
        view.setLayoutParams(lp);
        return view;
    }

    private View addNumView(Property property) {
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        LayoutInflater inflater3 = LayoutInflater.from(this);
        View view = inflater3.inflate(R.layout.add_num_view, null);
        TextView tvPropertyTitle = (TextView) view.findViewById(R.id.tv_property_title);
        EditText etPropertyValue = (EditText) view.findViewById(R.id.et_property_value);
        tvPropertyTitle.setText(property.getTitle());
        property.setTag(etPropertyValue);
        if (property.isRequired()) {
            etPropertyValue.setHint(R.string.add_work_log_property_num_isrequired_hint);
        } else {
            etPropertyValue.setHint(R.string.add_work_log_property_num_hint);
        }
        if (property.getValue() != null && flag.equals("check")) {
            etPropertyValue.setText(property.getValue());
            etPropertyValue.setEnabled(false);
        }
        etPropertyValue.setTag(property);
        inputValues.add(etPropertyValue);
        etPropertyValue.setOnFocusChangeListener(onFocusChangeListener);
        view.setLayoutParams(lp);
        return view;
    }

    private View addDateView(final Property property) {
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        LayoutInflater inflater3 = LayoutInflater.from(this);
        View view = inflater3.inflate(R.layout.add_date_view, null);
        TextView tvPropertyTitle = (TextView) view.findViewById(R.id.tv_property_title);
        tvPropertyTitle.setText(property.getTitle());
        RelativeLayout rlDateTimePick = (RelativeLayout) view.findViewById(R.id.rl_date_time_pick);
        final TextView tvDate = (TextView) view.findViewById(R.id.tv_date);
        property.setTag(tvDate);
        if (property.isRequired()) {
            String strTime = new SimpleDateFormat("yy-MM-dd HH:mm").format(new Date());
            tvDate.setText(strTime);
            property.setValue(strTime);
        } else {
            tvDate.setText(R.string.add_work_log_property_date_hint);
        }
        if (property.getValue() != null && flag.equals("check")) {
            tvDate.setText(property.getValue());
            tvDate.setEnabled(false);
            rlDateTimePick.setEnabled(false);
        }
        rlDateTimePick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CustomPickerDialog dateTimePicKDialog = new CustomPickerDialog(WorkLogAddActivity.this);
                dateTimePicKDialog.dateTimePicKDialog(tvDate, property);
            }
        });
        view.setLayoutParams(lp);
        return view;
    }

    private void setBar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("");
        TextView tv = (TextView) toolbar.findViewById(R.id.tv_toolbar);
        if (flag.equals("check")) {
            tv.setText(workLogTemp.getTitle());
        } else {
            tv.setText(R.string.activity_work_log_add_title);
        }
        ((ImageView) findViewById(R.id.iv_headicon)).setImageResource(R.drawable.toolbar_back);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                mHandler.sendEmptyMessage(EXIT);
//            }
//        });
        findViewById(R.id.iv_headicon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mHandler.sendEmptyMessage(EXIT);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        toolbar.setNavigationIcon(null);
    }



    @Override
    public void onNetworkInteractAllOver(int ret) {

    }

    @Override
    public void onNetworkInteractOver(int ret, String flag, Object object) {
        if (interactUtil.ADDWORKLOG.equals(flag)) {
            hideloadingDialog();
            if (ret == 0) {
                JSONObject jsonObject = (JSONObject) object;
                System.out.println("jsonObject=" + jsonObject.toString());
                showToast("添加成功");
                setResult(1);
                finish();
            } else {

            }
        }
    }
}
